package one.stand.controller;

import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.jmp.api.dto.CommentListResponse;
import com.jmp.api.dto.DynamicListRequest;
import com.jmp.autocofiguration.web.interceptor.SecurityAuthCheck;
import com.jmp.base.DynamicApi;
import com.jmp.base.dto.DynamicCommentRemoveDto;
import com.jmp.base.dto.DynamicCommentSaveDto;
import com.jmp.feign.CrmFegin;
import com.jmp.feign.DynamicFeign;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import one.stand.advice.ResultEnum;
import one.stand.dto.CommentDto;
import one.stand.dto.ConvertUtils;
import one.stand.dto.UserDto;
import one.stand.mapper.DynamicApiCrmMapper;
import one.stand.model.Company;
import one.stand.model.Dynamic;
import one.stand.model.ResultModel;
import one.stand.request.CommentRequest;
import one.stand.request.DynamicRequest;
import one.stand.response.CommentResponse;
import one.stand.response.DynamicResponse;
import one.stand.service.CompanyBaseService;
import one.stand.service.RecordPublicService;
import one.stand.service.user.UserAdminService;
import one.stand.util.AssertUtil;
import one.stand.util.RequestContext;
import one.stand.util.RequestContextHolder;
import org.apache.commons.lang3.BooleanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * @author cjr
 */
@Api(description = "动态、评论")
@RequestMapping("crmApi/company")
@RestController
public class DynamicController {

    @Autowired
    private CrmFegin crmFegin;
    @Autowired
    private DynamicFeign dynamicFeign;

    @Autowired
    private UserAdminService userAdminService;
    @Autowired
    private CompanyBaseService companyBaseService;
    @Autowired
    private RecordPublicService recordPublicService;

    @Autowired
    private DynamicApiCrmMapper dynamicApiCrmMapper;

    @ApiOperation(value = "查询公司动态/文章")
    @PostMapping("selectDynamicInfo")
    @SecurityAuthCheck(company = true, card = true)
    public ResultModel<List<DynamicResponse>> selectDynamicInfo(@RequestAttribute DynamicListRequest request) {
        if (request == null) {
            return ResultModel.checkParamFail();
        }

        final RequestContext.User optUser = RequestContextHolder.getRequestContext().getUser();

        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<Dynamic> list = dynamicApiCrmMapper.select(optUser.getUserId(),
                optUser.getCompanyId(),
                request.getDynamicId());
        if (list == null) {
            return ResultModel.noData();
        }

        UserDto user = userAdminService.get(optUser.getUserId());
        Company company = companyBaseService.getById(optUser.getCompanyId());

        List<DynamicResponse> responseList = new ArrayList<>();
        list.forEach(cl -> {
            {
                DynamicResponse dynamicResponse = new DynamicResponse();

                dynamicResponse.setDynamicId(cl.getDynamicId());
                dynamicResponse.setCompanyId(cl.getCompanyId());
                dynamicResponse.setTitle(cl.getTitle());
                dynamicResponse.setType(cl.getType());
                dynamicResponse.setPhotos(cl.getPhotos());
                dynamicResponse.setDetails(cl.getDetails());
                dynamicResponse.setCreateUserId(cl.getCreateUserId());
                dynamicResponse.setCreateTime(cl.getCreateTime());

                dynamicResponse.setNickeName(user.getName());
                dynamicResponse.setCommentNum(recordPublicService.countCommentByDynamic(dynamicResponse.getDynamicId()));
                dynamicResponse.setIsThumbs(BooleanUtils.toInteger(recordPublicService.isThumbs(user.getUserId(), RecordPublicService.THUMBS_TYPE_ARTICLE, dynamicResponse.getDynamicId())));
                dynamicResponse.setDoThumbsNum(recordPublicService.getThumbsCount(RecordPublicService.THUMBS_TYPE_ARTICLE, dynamicResponse.getDynamicId()));
                dynamicResponse.setDoThumbsName(recordPublicService.getThumbsNames(RecordPublicService.THUMBS_TYPE_ARTICLE, dynamicResponse.getDynamicId()));

                dynamicResponse.setUserId(company.getUserId());
                dynamicResponse.setCompanyName(company.getCompanyName());
                dynamicResponse.setCompanyLogo(company.getCompanyLogo());
                dynamicResponse.setCompanyPhone(company.getPhone());
                dynamicResponse.setCompanyNotice(company.getCompanyNotice());
                dynamicResponse.setIndustryId(String.valueOf(company.getIndustryId()));
                dynamicResponse.setRecruitPhone(company.getRecruitPhone());

                List<CommentDto> commentDtos = recordPublicService.getCommentList(dynamicResponse.getDynamicId(), 10);
                dynamicResponse.setCommentModelList(ConvertUtils.list(commentDtos, commentModel -> {
                    CommentResponse commentResponse = new CommentResponse();
                    commentResponse.setCommentId(commentModel.getCommentId());
                    commentResponse.setDynamicId(commentModel.getDynamicId());
                    commentResponse.setType(commentModel.getType());
                    commentResponse.setUserId(commentModel.getUserId());
                    commentResponse.setParentId(commentModel.getParentId());
                    commentResponse.setText(commentModel.getText());
                    commentResponse.setUserName(commentModel.getUserName());
                    commentResponse.setCoverUserId(commentModel.getCoverUserId());
                    commentResponse.setReplyName(commentModel.getReplyName());
                    return commentResponse;
                }));
                responseList.add(dynamicResponse);
            }
        });
        return ResultModel.success(responseList);
    }

    @ApiOperation(value = "查询公司动态/文章详细信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "dynamicId", value = "动态/文章id", required = true, paramType = "Integer"),
    })
    @PostMapping("getDynamicInfo")
    @SecurityAuthCheck(company = true, card = true)
    public ResultModel<List<DynamicResponse>> getDynamicInfo(@RequestAttribute DynamicListRequest request) {
        if (request == null) {
            return ResultModel.checkParamFail();
        }
        return selectDynamicInfo(request);
    }

    @ApiOperation(value = "添加/修改公司动态/文章")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "companyId", value = "企业id", required = true, paramType = "Integer"),
            @ApiImplicitParam(name = "title", value = "标题", required = true, paramType = "String"),
            @ApiImplicitParam(name = "type", value = "类型", required = true, paramType = "Integer"),
            @ApiImplicitParam(name = "photos", value = "图片", paramType = "String"),
            @ApiImplicitParam(name = "details", value = "详情", paramType = "String"),
    })
    @PostMapping("addDynamicInfo")
    @SecurityAuthCheck(company = true, card = true)
    public ResultModel addDynamicInfo(@RequestAttribute DynamicRequest request) {
        return crmFegin.addDynamicInfo(request);
    }

    @ApiOperation(value = "删除公司动态/文章")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "dynamicId", value = "文章、动态ID", required = true, paramType = "Integer"),
    })
    @PostMapping("delDynamicInfo")
    @SecurityAuthCheck(company = true, card = true)
    public ResultModel delDynamicInfo(@RequestAttribute DynamicRequest request) {
        return crmFegin.delDynamicInfo(request);
    }

    @ApiOperation(value = "查询所有评论/回复")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "dynamicId", value = "动态/文章id", required = true, paramType = "Integer")
    })
    @PostMapping("/selectComment")
    @SecurityAuthCheck(company = true, card = true)
    public ResultModel<List<CommentListResponse>> selectComment(@RequestAttribute CommentRequest request) {
        List<CommentDto> commentDtos = recordPublicService.getCommentList(request.getDynamicId(), null);
        List<CommentListResponse> responseList = ConvertUtils.list(commentDtos, commentDto -> {
            return CommentListResponse.builder()
                    .commentId(commentDto.getCommentId())
                    .dynamicId(commentDto.getDynamicId())
                    .userId(commentDto.getUserId())
                    .userName(commentDto.getUserName())
                    .text(commentDto.getText())
                    .parentId(commentDto.getParentId())
                    .coverUserId(commentDto.getCoverUserId())
                    .replyName(commentDto.getReplyName())
                    .build();
        });
        return ResultModel.success(responseList);
    }

    @ApiOperation(value = "crm回复评论")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "dynamicId", value = "动态/文章id", required = true, paramType = "Integer"),
            @ApiImplicitParam(name = "parentId", value = "父级ID（评论为0，回复为对应评论ID）", required = true, paramType = "Integer"),
            @ApiImplicitParam(name = "text", value = "内容", required = true, paramType = "String"),
    })
    @PostMapping("/doComment")
    @SecurityAuthCheck(company = true, card = true)
    public ResultModel doComment(@RequestAttribute CommentRequest request) {
        RequestContext.User optUser = RequestContextHolder.getRequestContext().getUser();
        DynamicCommentSaveDto saveDto = DynamicCommentSaveDto.builder()
                .commentType(DynamicApi.COMMENT_TYPE_ARTICEL)
                .dynamicId(request.getDynamicId())
                .parentId(request.getParentId())
                .userId(optUser.getUserId())
                .text(request.getText())
                .build();
        ResultModel resultModel = dynamicFeign.commentSave(saveDto);
        AssertUtil.isTrue(resultModel);

        return ResultModel.success();
    }

    @ApiOperation(value = "crm删除评论")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "commentId", value = "评论表ID", required = true, paramType = "Integer"),
    })
    @PostMapping("/delComment")
    @SecurityAuthCheck(company = true, card = true)
    public ResultModel delComment(@RequestAttribute CommentRequest request) {
        AssertUtil.nonNull(request.getCommentId(), ResultEnum.PARAM_CHECK, "评论ID不能为空");

        RequestContext.User optUser = RequestContextHolder.getRequestContext().getUser();

        ResultModel resultModel = dynamicFeign.commentRemove(DynamicCommentRemoveDto.builder()
                .commentIds(Lists.newArrayList(request.getCommentId()))
                .userId(optUser.getUserId())
                .build());
        AssertUtil.isTrue(resultModel);

        return ResultModel.success();
    }
}
